<template>
  <AdminLayout title="编辑产品" subtitle="修改产品信息和规格配置">
    <form @submit.prevent="submit">
      <!-- 左右分栏布局 -->
      <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">
        
        <!-- 左侧栏 - 固定宽度 (5列) -->
        <div class="lg:col-span-5 space-y-6">
          
          <!-- 基本信息 -->
          <div class="bg-white shadow-sm rounded-lg">
          <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">基本信息</h3>
          </div>
          
          <div class="px-6 py-4 space-y-6">
            <!-- 产品名称 -->
            <div>
              <label for="name" class="block text-sm font-medium text-gray-700">
                产品名称 <span class="text-red-500">*</span>
              </label>
              <input 
                id="name"
                v-model="form.name"
                type="text" 
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                :class="{ 'border-red-300': errors.name }"
                placeholder="请输入产品名称"
              />
              <p v-if="errors.name" class="mt-1 text-sm text-red-600">{{ errors.name }}</p>
            </div>

            <!-- 产品别名 -->
            <div>
              <label for="slug" class="block text-sm font-medium text-gray-700">
                产品别名 <span class="text-red-500">*</span>
              </label>
              <input 
                id="slug"
                v-model="form.slug"
                type="text" 
                readonly
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm bg-gray-50 text-gray-500 cursor-not-allowed sm:text-sm"
                placeholder="产品别名（不可修改）"
              />
              <p v-if="errors.slug" class="mt-1 text-sm text-red-600">{{ errors.slug }}</p>
              <p class="mt-1 text-sm text-gray-500">用于URL的标识符，只能包含字母、数字和连字符</p>
            </div>

            <!-- 产品SKU -->
            <div>
              <label for="sku" class="block text-sm font-medium text-gray-700">
                产品SKU <span class="text-red-500">*</span>
              </label>
              <input 
                id="sku"
                v-model="form.sku"
                type="text" 
                readonly
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm bg-gray-50 text-gray-500 cursor-not-allowed sm:text-sm"
                placeholder="产品SKU（不可修改）"image.png
              />
              <p v-if="errors.sku" class="mt-1 text-sm text-red-600">{{ errors.sku }}</p>
            </div>

            <!-- 产品简短描述 -->
            <div>
              <label for="description" class="block text-sm font-medium text-gray-700">简短描述</label>
              <textarea 
                id="description"
                v-model="form.description"
                rows="3"
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                :class="{ 'border-red-300': errors.description }"
                placeholder="请输入产品简短描述（用于列表页展示）"
              ></textarea>
              <p v-if="errors.description" class="mt-1 text-sm text-red-600">{{ errors.description }}</p>
            </div>

            <!-- 详细描述 -->
            <div>
              <label for="long_description" class="block text-sm font-medium text-gray-700">详细描述</label>
              <textarea 
                id="long_description"
                v-model="form.long_description"
                rows="8"
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                :class="{ 'border-red-300': errors.long_description }"
                placeholder="请输入产品详细描述（支持多行文本）"
              ></textarea>
              <p v-if="errors.long_description" class="mt-1 text-sm text-red-600">{{ errors.long_description }}</p>
              <p class="mt-1 text-sm text-gray-500">产品的详细介绍，将在产品详情页展示</p>
            </div>

            <!-- 产品分类 -->
            <div>
              <label class="block text-sm font-medium text-gray-700">
                产品分类 <span class="text-red-500">*</span>
              </label>
              <div class="mt-2 space-y-2">
                <div v-for="category in categories" :key="category.id" class="flex items-center">
                  <input 
                    :id="`category-${category.id}`"
                    v-model="form.category_ids"
                    :value="category.id"
                    type="checkbox"
                    disabled
                    class="h-4 w-4 text-gray-400 border-gray-300 rounded cursor-not-allowed"
                  />
                  <label :for="`category-${category.id}`" class="ml-2 text-sm text-gray-500">
                    {{ category.name }}
                  </label>
                </div>
              </div>
              <p class="mt-2 text-sm text-gray-500">产品分类不可修改，如需修改请联系系统管理员</p>
              <p v-if="errors.category_ids" class="mt-1 text-sm text-red-600">{{ errors.category_ids }}</p>
            </div>
          </div>
        </div>

        <!-- 价格设置 -->
        <div class="bg-white shadow-sm rounded-lg">
          <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">价格设置</h3>
          </div>
          
          <div class="px-6 py-4 space-y-6">
            <!-- 销售价格 -->
            <div>
              <label for="price" class="block text-sm font-medium text-gray-700">
                销售价格 <span class="text-red-500">*</span>
              </label>
              <div class="mt-1 relative rounded-md shadow-sm">
                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <span class="text-gray-500 sm:text-sm">¥</span>
                </div>
                <input 
                  id="price"
                  v-model="form.price"
                  type="number" 
                  step="0.01"
                  min="0"
                  class="pl-7 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                  :class="{ 'border-red-300': errors.price }"
                  placeholder="0.00"
                />
              </div>
              <p v-if="errors.price" class="mt-1 text-sm text-red-600">{{ errors.price }}</p>
            </div>

            <!-- 原价 -->
            <div>
              <label for="compare_price" class="block text-sm font-medium text-gray-700">原价</label>
              <div class="mt-1 relative rounded-md shadow-sm">
                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <span class="text-gray-500 sm:text-sm">¥</span>
                </div>
                <input 
                  id="compare_price"
                  v-model="form.compare_price"
                  type="number" 
                  step="0.01"
                  min="0"
                  class="pl-7 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                  :class="{ 'border-red-300': errors.compare_price }"
                  placeholder="0.00"
                />
              </div>
              <p v-if="errors.compare_price" class="mt-1 text-sm text-red-600">{{ errors.compare_price }}</p>
              <p class="mt-1 text-sm text-gray-500">用于显示折扣，留空则不显示折扣标签。若设置，必须高于销售价格</p>
            </div>
          </div>
        </div>

        <!-- 产品类型 -->
        <div class="bg-white shadow-sm rounded-lg">
          <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">产品类型</h3>
          </div>
          
          <div class="px-6 py-4">
            <div class="space-y-4">
              <div class="flex items-center">
                <input 
                  id="single" 
                  v-model="form.product_type" 
                  value="single" 
                  type="radio" 
                  disabled
                  class="h-4 w-4 text-gray-400 border-gray-300 cursor-not-allowed"
                />
                <label for="single" class="ml-2 text-sm text-gray-500">单规格产品</label>
              </div>
              <div class="flex items-center">
                <input 
                  id="multi_variant" 
                  v-model="form.product_type" 
                  value="multi_variant" 
                  type="radio" 
                  disabled
                  class="h-4 w-4 text-gray-400 border-gray-300 cursor-not-allowed"
                />
                <label for="multi_variant" class="ml-2 text-sm text-gray-500">多规格产品</label>
              </div>
            </div>
            <p class="mt-2 text-sm text-gray-500">产品类型不可修改，如需修改请联系系统管理员</p>
            <p v-if="errors.product_type" class="mt-1 text-sm text-red-600">{{ errors.product_type }}</p>
          </div>
        </div>

        <!-- 单规格产品库存 -->
        <div v-if="form.product_type === 'single'" class="bg-white shadow-sm rounded-lg">
          <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">库存设置</h3>
          </div>
          
          <div class="px-6 py-4">
            <div>
              <label for="stock_quantity" class="block text-sm font-medium text-gray-700">库存数量</label>
              <input 
                id="stock_quantity"
                v-model="form.stock_quantity"
                type="number" 
                min="0"
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                :class="{ 'border-red-300': errors.stock_quantity }"
                placeholder="请输入库存数量"
              />
              <p v-if="errors.stock_quantity" class="mt-1 text-sm text-red-600">{{ errors.stock_quantity }}</p>
            </div>
          </div>
        </div>

        <!-- 状态设置 -->
        <div class="bg-white shadow-sm rounded-lg">
          <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">状态设置</h3>
          </div>
          
          <div class="px-6 py-4 space-y-4">
            <div class="flex items-center">
              <input 
                id="is_active" 
                v-model="form.is_active" 
                type="checkbox"
                class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded"
              />
              <label for="is_active" class="ml-2 block text-sm text-gray-700">
                启用产品
              </label>
            </div>
            
            <div class="flex items-center">
              <input 
                id="is_featured" 
                v-model="form.is_featured" 
                type="checkbox"
                class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded"
              />
              <label for="is_featured" class="ml-2 block text-sm text-gray-700">
                推荐产品
              </label>
            </div>
          </div>
        </div>

        <!-- 图片管理 -->
        <div class="bg-white shadow-sm rounded-lg" :class="{ 'ring-2 ring-blue-500': highlightImages }">
          <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">产品图片</h3>
          </div>
          
          <div class="px-6 py-4">
            <ImageManager resource-type="products" :resource-id="product.id" />
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="flex items-center justify-end gap-4">
          <Link 
            :href="route('admin.products.index')"
            class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors"
          >
            取消
          </Link>
          <button 
            type="submit" 
            :disabled="processing"
            class="px-4 py-2 border border-transparent rounded-md text-sm font-medium text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {{ processing ? '保存中...' : '保存产品' }}
          </button>
        </div>

      </div>
      <!-- 左侧栏结束 -->

      <!-- 右侧栏 - 自适应宽度 (7列) -->
        <div class="lg:col-span-7 space-y-6">
          
          <!-- 产品特性 - 可折叠 -->
          <div class="bg-white shadow-sm rounded-lg">
            <button
              type="button"
              @click="toggleSection('features')"
              class="w-full px-6 py-4 flex items-center justify-between border-b border-gray-200 hover:bg-gray-50 transition-colors"
            >
              <h3 class="text-lg font-medium text-gray-900">产品特性</h3>
              <svg 
                class="w-5 h-5 text-gray-500 transition-transform"
                :class="{ 'transform rotate-180': expandedSections.features }"
                fill="none" 
                stroke="currentColor" 
                viewBox="0 0 24 24"
              >
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
              </svg>
            </button>
            
            <div v-show="expandedSections.features" class="px-6 py-4">
              <label class="block text-sm font-medium text-gray-700 mb-2">产品特性列表</label>
              <div class="space-y-2">
                <div v-for="(feature, index) in form.features" :key="index" class="flex gap-2">
                  <input 
                    v-model="form.features[index]"
                    type="text"
                    class="flex-1 border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                    placeholder="请输入产品特性"
                  />
                  <button 
                    type="button"
                    @click="removeFeature(index)"
                    class="px-3 py-2 text-sm text-red-600 hover:text-red-700"
                  >
                    删除
                  </button>
                </div>
              </div>
              <button 
                type="button"
                @click="addFeature"
                class="mt-2 text-sm text-gray-600 hover:text-gray-900"
              >
                + 添加特性
              </button>
              <p class="mt-2 text-sm text-gray-500">产品的核心特点，以列表形式展示</p>
            </div>
          </div>

          <!-- 技术规格 - 可折叠 -->
          <div class="bg-white shadow-sm rounded-lg">
            <button
              type="button"
              @click="toggleSection('specs')"
              class="w-full px-6 py-4 flex items-center justify-between border-b border-gray-200 hover:bg-gray-50 transition-colors"
            >
              <h3 class="text-lg font-medium text-gray-900">技术规格</h3>
              <svg 
                class="w-5 h-5 text-gray-500 transition-transform"
                :class="{ 'transform rotate-180': expandedSections.specs }"
                fill="none" 
                stroke="currentColor" 
                viewBox="0 0 24 24"
              >
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
              </svg>
            </button>
            
            <div v-show="expandedSections.specs" class="px-6 py-4">
              <label class="block text-sm font-medium text-gray-700 mb-3">技术参数</label>
              <div class="space-y-4">
                <div v-for="(spec, specIndex) in form.technical_specs" :key="specIndex" class="border border-gray-200 rounded-md p-4">
                  <div class="flex items-center justify-between mb-3">
                    <input 
                      v-model="spec.category"
                      type="text"
                      class="flex-1 border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                      placeholder="规格分类（如：显示屏、芯片与性能）"
                    />
                    <button 
                      type="button"
                      @click="removeSpecCategory(specIndex)"
                      class="ml-2 px-3 py-2 text-sm text-red-600 hover:text-red-700"
                    >
                      删除分类
                    </button>
                  </div>
                  <div class="space-y-2">
                    <div v-for="(item, itemIndex) in spec.items" :key="itemIndex" class="flex gap-2">
                      <input 
                        v-model="item.name"
                        type="text"
                        class="w-1/3 border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                        placeholder="参数名称"
                      />
                      <input 
                        v-model="item.value"
                        type="text"
                        class="flex-1 border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                        placeholder="参数值"
                      />
                      <button 
                        type="button"
                        @click="removeSpecItem(specIndex, itemIndex)"
                        class="px-3 py-2 text-sm text-red-600 hover:text-red-700"
                      >
                        删除
                      </button>
                    </div>
                  </div>
                  <button 
                    type="button"
                    @click="addSpecItem(specIndex)"
                    class="mt-2 text-sm text-gray-600 hover:text-gray-900"
                  >
                    + 添加参数
                  </button>
                </div>
              </div>
              <button 
                type="button"
                @click="addSpecCategory"
                class="mt-4 text-sm text-gray-600 hover:text-gray-900"
              >
                + 添加规格分类
              </button>
              <p class="mt-2 text-sm text-gray-500">产品的技术参数，按分类组织展示</p>
            </div>
          </div>

          <!-- 旧的产品特性区块开始 - 需要删除 -->
          <div style="display:none">
            <!-- 产品分类 -->
            <div>
              <label class="block text-sm font-medium text-gray-700">产品特性</label>
              <div class="mt-2 space-y-2">
                <div v-for="(feature, index) in form.features" :key="index" class="flex gap-2">
                  <input 
                    v-model="form.features[index]"
                    type="text"
                    class="flex-1 border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                    placeholder="请输入产品特性"
                  />
                  <button 
                    type="button"
                    @click="removeFeature(index)"
                    class="px-3 py-2 text-sm text-red-600 hover:text-red-700"
                  >
                    删除
                  </button>
                </div>
              </div>
              <button 
                type="button"
                @click="addFeature"
                class="mt-2 text-sm text-gray-600 hover:text-gray-900"
              >
                + 添加特性
              </button>
              <p class="mt-1 text-sm text-gray-500">产品的核心特点，以列表形式展示</p>
            </div>

            <!-- 技术规格 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">技术规格</label>
              <div class="space-y-4">
                <div v-for="(spec, specIndex) in form.technical_specs" :key="specIndex" class="border border-gray-200 rounded-md p-4">
                  <div class="flex items-center justify-between mb-3">
                    <input 
                      v-model="spec.category"
                      type="text"
                      class="flex-1 border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                      placeholder="规格分类（如：显示屏、芯片与性能）"
                    />
                    <button 
                      type="button"
                      @click="removeSpecCategory(specIndex)"
                      class="ml-2 px-3 py-2 text-sm text-red-600 hover:text-red-700"
                    >
                      删除分类
                    </button>
                  </div>
                  <div class="space-y-2">
                    <div v-for="(item, itemIndex) in spec.items" :key="itemIndex" class="flex gap-2">
                      <input 
                        v-model="item.name"
                        type="text"
                        class="w-1/3 border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                        placeholder="参数名称"
                      />
                      <input 
                        v-model="item.value"
                        type="text"
                        class="flex-1 border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                        placeholder="参数值"
                      />
                      <button 
                        type="button"
                        @click="removeSpecItem(specIndex, itemIndex)"
                        class="px-3 py-2 text-sm text-red-600 hover:text-red-700"
                      >
                        删除
                      </button>
                    </div>
                    <button 
                      type="button"
                      @click="addSpecItem(specIndex)"
                      class="text-sm text-gray-600 hover:text-gray-900"
                    >
                      + 添加参数
                    </button>
                  </div>
                </div>
              </div>
              <button 
                type="button"
                @click="addSpecCategory"
                class="mt-3 text-sm text-gray-600 hover:text-gray-900"
              >
                + 添加规格分类
              </button>
              <p class="mt-1 text-sm text-gray-500">产品的技术参数，按分类组织展示</p>
            </div>

            <!-- 产品分类 -->
            <div>
              <label class="block text-sm font-medium text-gray-700">
                产品分类 <span class="text-red-500">*</span>
              </label>
              <div class="mt-2 space-y-2">
                <div v-for="category in categories" :key="category.id" class="flex items-center">
                  <input 
                    :id="`category-${category.id}`"
                    v-model="form.category_ids"
                    :value="category.id"
                    type="checkbox"
                    disabled
                    class="h-4 w-4 text-gray-400 border-gray-300 rounded cursor-not-allowed"
                  />
                  <label :for="`category-${category.id}`" class="ml-2 text-sm text-gray-500">
                    {{ category.name }}
                  </label>
                </div>
              </div>
              <p class="mt-2 text-sm text-gray-500">产品分类不可修改，如需修改请联系系统管理员</p>
              <p v-if="errors.category_ids" class="mt-1 text-sm text-red-600">{{ errors.category_ids }}</p>
            </div>
          </div>
          <!-- 旧区块结束 -->

          <!-- 多规格配置 - 默认展开 -->
          <div v-if="form.product_type === 'multi_variant'" class="bg-white shadow-sm rounded-lg">
            <button
              type="button"
              @click="toggleSection('variants')"
              class="w-full px-6 py-4 flex items-center justify-between border-b border-gray-200 hover:bg-gray-50 transition-colors"
            >
              <h3 class="text-lg font-medium text-gray-900">多规格配置</h3>
              <svg 
                class="w-5 h-5 text-gray-500 transition-transform"
                :class="{ 'transform rotate-180': expandedSections.variants }"
                fill="none" 
                stroke="currentColor" 
                viewBox="0 0 24 24"
              >
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
              </svg>
            </button>
            
            <div v-show="expandedSections.variants" class="px-6 py-4">
              <!-- 规格模板选择 -->
              <div v-if="form.category_ids.length > 0" class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-3">规格模板选择</label>
                <div class="space-y-2">
                  <div v-for="template in filteredTemplates" :key="template.id" class="flex items-center">
                    <input 
                      :id="`template-${template.id}`"
                      v-model="selectedTemplate"
                      :value="template.id"
                      type="radio"
                      disabled
                      class="h-4 w-4 text-gray-400 border-gray-300 cursor-not-allowed"
                    />
                    <label :for="`template-${template.id}`" class="ml-2 text-sm text-gray-500">
                      {{ template.name }}
                      <span class="text-gray-400">({{ template.category_name }})</span>
                    </label>
                  </div>
                </div>
                <p class="mt-2 text-sm text-gray-500">规格模板不可修改，如需修改请联系系统管理员</p>
              </div>

              <!-- 变体管理 -->
              <div v-if="product.variants && product.variants.length > 0">
                <div class="flex items-center justify-between mb-4">
                  <h4 class="text-md font-medium text-gray-900">现有规格型号</h4>
                  <Link :href="route('admin.products.variants', product.id)" 
                        class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900">
                    管理规格型号
                  </Link>
                </div>
                
                <div class="space-y-3">
                  <div v-for="variant in product.variants" :key="variant.id" 
                       class="border border-gray-200 rounded-lg p-4">
                    <div class="flex items-center justify-between mb-2">
                      <h5 class="font-medium text-gray-900">{{ variant.name }}</h5>
                      <div class="flex items-center space-x-4">
                        <div class="flex items-center space-x-2">
                          <span class="text-sm text-gray-500">SKU: {{ variant.sku }}</span>
                          <span class="text-sm text-gray-500">|</span>
                          <span class="text-sm text-gray-500">库存: 
                            <span :class="{
                              'text-green-600 font-medium': variant.stock_quantity > 10,
                              'text-yellow-600 font-medium': variant.stock_quantity > 0 && variant.stock_quantity <= 10,
                              'text-red-600 font-medium': variant.stock_quantity === 0
                            }">
                              {{ variant.stock_quantity }}
                            </span>
                          </span>
                        </div>
                        <button
                          type="button"
                          @click="openQuickEditModal(variant)"
                          class="text-sm text-blue-600 hover:text-blue-700"
                        >
                          快速编辑
                        </button>
                      </div>
                    </div>
                    <div class="text-sm text-gray-600">
                      <span class="font-medium">销售价格:</span> ¥{{ variant.price }}
                      <span v-if="variant.compare_price" class="ml-4">
                        <span class="font-medium">原价:</span> ¥{{ variant.compare_price }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

        </div>
        <!-- 右侧栏结束 -->

      </div>
      <!-- 网格布局结束 -->
    </form>

    <!-- 快速编辑模态框 -->
    <div v-if="showQuickEditModal" class="fixed inset-0 z-50 overflow-y-auto">
      <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <!-- 背景遮罩 -->
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
          <div class="absolute inset-0 bg-gray-500 opacity-75" @click="closeQuickEditModal"></div>
        </div>

        <!-- 模态框内容 -->
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
          <div>
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
              <div class="sm:flex sm:items-start">
                <div class="w-full">
                  <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">
                    快速编辑规格型号
                  </h3>
                  
                  <div class="space-y-4">
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-1">SKU</label>
                      <input 
                        :value="editingVariant?.sku"
                        type="text" 
                        readonly
                        class="w-full border-gray-300 rounded-md shadow-sm bg-gray-50 text-sm"
                      />
                    </div>
                    
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-1">价格</label>
                      <input 
                        v-model="quickEditForm.price"
                        type="number" 
                        step="0.01"
                        min="0"
                        class="w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 text-sm"
                        placeholder="0.00"
                        required
                      />
                    </div>
                    
                       <div>
                         <label class="block text-sm font-medium text-gray-700 mb-1">原价</label>
                         <input 
                           v-model="quickEditForm.compare_price"
                           type="number" 
                           step="0.01"
                           min="0"
                           class="w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 text-sm"
                           placeholder="0.00"
                         />
                         <p class="mt-1 text-xs text-gray-500">
                           留空表示无折扣
                         </p>
                       </div>
                    
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-1">库存数量</label>
                      <input 
                        v-model.number="quickEditForm.stock_quantity"
                        type="number" 
                        min="0"
                        class="w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 text-sm"
                        placeholder="0"
                        required
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
              <button 
                type="button"
                @click="updateVariantQuick"
                :disabled="updatingVariant"
                class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-gray-900 text-base font-medium text-white hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 sm:ml-3 sm:w-auto sm:text-sm disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {{ updatingVariant ? '保存中...' : '保存' }}
              </button>
              <button 
                type="button"
                @click="closeQuickEditModal"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
              >
                取消
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </AdminLayout>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { Link, useForm, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { useNotification } from '@/composables/useNotification'
import ImageManager from '@/Components/ImageManager.vue'

// 定义 props
const props = defineProps({
  product: {
    type: Object,
    required: true
  },
  categories: {
    type: Array,
    required: true
  },
  specificationTemplates: {
    type: Array,
    default: () => []
  }
})

const { showError, showSuccess } = useNotification()
const highlightImages = ref(false)

// 处理状态
const processing = ref(false)
const selectedTemplate = ref(props.product.template?.id || props.product.template_id || null)

// 折叠面板状态
const expandedSections = reactive({
  features: false,      // 产品特性 - 默认折叠
  specs: false,         // 技术规格 - 默认折叠
  variants: true        // 多规格配置 - 默认展开
})

// 切换折叠面板
const toggleSection = (section) => {
  expandedSections[section] = !expandedSections[section]
}

// 快速编辑模态框相关状态
const showQuickEditModal = ref(false)
const editingVariant = ref(null)
const updatingVariant = ref(false)
const quickEditForm = reactive({
  price: '',
  compare_price: '',
  stock_quantity: 0
})

// 表单数据
const form = useForm({
  name: props.product.name,
  slug: props.product.slug,
  sku: props.product.sku,
  description: props.product.description || '',
  long_description: props.product.long_description || '',
  features: props.product.features || [],
  technical_specs: (props.product.meta_data && props.product.meta_data.technical_specs) || [],
  price: props.product.price,
  compare_price: props.product.compare_price || '',
  product_type: props.product.product_type,
  is_active: props.product.is_active,
  is_featured: props.product.is_featured,
  stock_quantity: props.product.stock_quantity || 0,
  category_ids: props.product.categories ? props.product.categories.map(cat => cat.id) : []
})

// 计算属性
const errors = computed(() => form.errors)

// 过滤后的规格模板
const filteredTemplates = computed(() => {
  if (form.category_ids.length === 0) return []
  
  return props.specificationTemplates.filter(template => 
    !template.category_id || form.category_ids.includes(template.category_id)
  )
})

// 提交表单
// 产品特性管理
const addFeature = () => {
  form.features.push('')
}

const removeFeature = (index) => {
  form.features.splice(index, 1)
}

// 技术规格管理
const addSpecCategory = () => {
  form.technical_specs.push({
    category: '',
    items: [{ name: '', value: '' }]
  })
}

const removeSpecCategory = (index) => {
  form.technical_specs.splice(index, 1)
}

const addSpecItem = (specIndex) => {
  form.technical_specs[specIndex].items.push({ name: '', value: '' })
}

const removeSpecItem = (specIndex, itemIndex) => {
  form.technical_specs[specIndex].items.splice(itemIndex, 1)
}

const submit = () => {
  processing.value = true
  
  form.put(route('admin.products.update', props.product.id), {
    onSuccess: () => {
      processing.value = false
      // 后端已经发送了 flash 消息，这里不需要重复显示
    },
    onError: (errors) => {
      processing.value = false
      
      // 显示第一个错误信息
      const firstError = Object.values(errors)[0]
      if (firstError) {
        showError('产品更新失败', Array.isArray(firstError) ? firstError[0] : firstError)
      } else {
        showError('产品更新失败', '请检查表单信息')
      }
    },
    onFinish: () => {
      processing.value = false
    }
  })
}

// 快速编辑变体相关方法
const openQuickEditModal = (variant) => {
  editingVariant.value = variant
  quickEditForm.price = variant.price
  quickEditForm.compare_price = variant.compare_price
  quickEditForm.stock_quantity = variant.stock_quantity
  showQuickEditModal.value = true
}

// 图片管理逻辑已抽离到组件

// 创建成功引导：如后端带了 highlight_section=images，则滚动并高亮图片区域
if (typeof window !== 'undefined') {
  const page = router.page || null
  const highlight = page?.props?.flash?.highlight_section || null
  if (highlight === 'images') {
    setTimeout(() => {
      const el = document.getElementById('images')
      if (el) {
        el.scrollIntoView({ behavior: 'smooth', block: 'start' })
        highlightImages.value = true
        setTimeout(() => (highlightImages.value = false), 2000)
      }
    }, 50)
  }
}

const closeQuickEditModal = () => {
  showQuickEditModal.value = false
  editingVariant.value = null
  quickEditForm.price = ''
  quickEditForm.compare_price = ''
  quickEditForm.stock_quantity = 0
}

const updateVariantQuick = () => {
  if (!editingVariant.value) return
  
  updatingVariant.value = true
  
  // 使用 Inertia.js router.put 方法，成功后重载产品数据
  router.put(route('admin.variants.update', editingVariant.value.id), {
    price: quickEditForm.price,
    compare_price: quickEditForm.compare_price,
    stock_quantity: quickEditForm.stock_quantity,
  }, {
    preserveState: true,
    preserveScroll: true,
    onSuccess: () => {
      // 后端已经发送了 flash 消息，这里不需要重复显示
      // 关闭模态框
      closeQuickEditModal()
      // 重载产品数据以获取最新的变体信息
      router.reload({ only: ['product'] })
      updatingVariant.value = false
    },
    onError: (errors) => {
      console.error('Errors:', errors)
      showError('更新失败', '规格型号信息更新失败，请重试')
      updatingVariant.value = false
    }
  })
}
</script>
